package com.joysuch.wwyt.app.service.impl;

import com.alibaba.fastjson.JSON;
import com.joysuch.wwyt.app.service.AppRiskCompanyService;
import com.joysuch.wwyt.bp.bean.risk.BpSpecialWorkTypeBean;
import com.joysuch.wwyt.bp.bean.risk.BpTeamSpecialBean;
import com.joysuch.wwyt.bp.entity.risk.BpReportSetting;
import com.joysuch.wwyt.bp.service.BpReportSettingService;
import com.joysuch.wwyt.bp.service.BpRiskCompanyService;
import com.joysuch.wwyt.core.common.ajax.ResultBean;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.util.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author ZhangDong
 * @Date 2020/6/22 11:20
 */
@Service
@Slf4j
public class AppRiskCompanyServiceImpl implements AppRiskCompanyService {

    @Autowired
    private BpRiskCompanyService bpRiskCompanyService;
    @Autowired
    private BpReportSettingService bpReportSettingService;

    @Override
    public ResultBean queryAnnounce(LocalDate announceTime) {
        announceTime = announceTime == null ? LocalDate.now() : announceTime;
        BpReportSetting setting = (BpReportSetting) bpReportSettingService.getById(0L).getData();
        Assert.notNull(setting, "请先配置'上报配置'");
        String specialWorkType = setting.getSpecialWorkType();
        List<BpSpecialWorkTypeBean> typeBeans = JSON.parseArray(specialWorkType, BpSpecialWorkTypeBean.class);
        Iterator<BpSpecialWorkTypeBean> iterator = typeBeans.iterator();
        //剔除配置中没勾选的
        while (iterator.hasNext()) {
            if (Boolean.FALSE.equals(iterator.next().getUseOrNot())) {
                iterator.remove();
            }
        }
        List<BpTeamSpecialBean> bpTeamSpecialBeans = (List<BpTeamSpecialBean>) bpRiskCompanyService.showData(announceTime).getData();
        if (bpTeamSpecialBeans == null) {
            setting.setSpecialWorkType(JSON.toJSONString(typeBeans));
            return ResultBean.wrapSuccessfulResult(setting);
        }
        Map<String, Integer> map = bpTeamSpecialBeans.stream()
                .collect(Collectors.toMap(BpTeamSpecialBean::getSpecialWorkName, BpTeamSpecialBean::getSum));
        for (BpSpecialWorkTypeBean bean : typeBeans) {
            bean.setSum(map.get(bean.getSpecialWorkName()));
        }
        setting.setSpecialWorkType(JSON.toJSONString(typeBeans));
        return ResultBean.wrapSuccessfulResult(setting);
    }
}
